﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Framework.Library.Base.Base;
using Framework.Library.Base.DataAccess;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Config;
using Framework.Library.Core.Utils;
using Framework.Library.Core.Utils.Images;
using Framework.Library.Core.Utils.Text;
using Framework.Library.Data.DAL;
using Framework.Library.Data.DAO;
using Framework.Library.Data.DAL.JObject;

namespace Framework.Portal.Layouts.Admin.Components.Teenio.Author
{
    public partial class CreateContent : BaseControl
    {
        private readonly string MENUNAME = string.Empty;
        private int typeCreator;

        public CreateContent()
        {
        }

        public CreateContent(JSection section)
        {
            MENUNAME = section.title;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            typeCreator = ManagerFactory.TeenioPermissionManager.CheckUserPermision(currentUserId,
                                                                                     Session.WorkingPortal().PORTALID);
            txtDatetime.Text = DateTime.Now.ToString();
            lblAlias.Text = Session.GetUser().DISPLAYNAME;
            if (!IsPostBack)
            {
                txtAvatar2Height.Text = cfg.ListHeight.VALUE;
                txtAvatar2width.Text = cfg.ListWidth.VALUE;
                txtSpecialAvatarHeight.Text = cfg.SpecialHeight.VALUE;
                txtSpecialAvatarwidth.Text = cfg.SpecialWidth.VALUE;

                lblUpdateStatus.Text = string.Empty;

                if (typeCreator > 1)
                    drpContentRank.Enabled = true;
                else
                    drpContentRank.Enabled = true;
                lblCommandName.Text = MENUNAME;
                drpContentType.DataSource = StaticData.ArticleType;
                drpContentRank.DataSource = StaticData.ArticleRank;
                drpContentType.DataBind();
                drpContentRank.DataBind();
                LoadMenus();
                LoadZones();
                int articleId;
                int.TryParse(Request.QueryString["a"], out articleId);
                if (articleId > 0)
                {
                    TeenioContent info = ManagerFactory.TeenioContentManager.GetInfo(articleId);
                    if (info != null)
                    {
                        LoadData(info);
                        cmdAdd.CommandArgument = info.CONTENT_ID.ToString();
                        cmdAdd.CommandName = "edit";
                        cmdSave.CommandArgument = info.CONTENT_ID.ToString();
                        cmdSave.CommandName = "edit";
                    }
                }
            }
        }

        private void LoadZones()
        {
            List<TeenioZone> dtPerspective = ManagerFactory.DAOEntity.GetList(new TeenioZone() { TYPE = Convert.ToInt32(drpContentType.SelectedValue) });
            if (dtPerspective != null)
            {
                CmsAccess.LoadZones(dtPerspective, drpPerspective.Items);
            }
            else
            {
                drpPerspective.Items.Clear();
                drpPerspective.Items.Add(new ListItem("Root", "0"));
            }
        }

        private void LoadMenus()
        {
            dropZones.Items.Clear();
            List<TeenioCategory> dt = ManagerFactory.TeenioCategoryManager.GetCategoriesByPortal(Session.WorkingPortal().PORTALID);
            if (dt != null)
            {
                CmsAccess.LoadCategories(dt, dropZones.Items);
                TeenioPermission curPermision =
                    ManagerFactory.TeenioPermissionManager.GetPermision(currentUserId, Session.WorkingPortal().PORTALID);
                if (curPermision != null)
                {
                    string permisionZoneCollection = curPermision.ZONES;
                    if (!string.IsNullOrEmpty(permisionZoneCollection))
                    {
                        int i = 0;
                        while (i < dropZones.Items.Count)
                        {
                            if (permisionZoneCollection.IndexOf("|" + dropZones.Items[i].Value + "|") < 0)
                                dropZones.Items.RemoveAt(i);
                            else
                                i += 1;
                        }
                    }
                    else
                        dropZones.Items.Clear();
                }
            }
        }

        private TeenioContent GetContent()
        {            
            var info = new TeenioContent();
            info.CONTENT_HEADLINE = txtHeadline.Text.Replace("&nbsp;", " ");
            info.CONTENT_TEASER = txtTeaser.Text.Replace("&nbsp;", " ");
            info.CONTENT_BODY = StringUtils.RemoveHtml(txtRawContent.Value);
            info.CONTENT_PREAVATAR = txtSpecialAvatar.Text;
            info.CONTENT_AVATAR = txtAvatar.Text;
            info.CONTENT_AVATARDESCRIPTION = txtAvatarDes.Text;
            info.CONTENT_SOURCE = txtSource.Text;
            info.CONTENT_METADATA = txtNoteBox.Text;
            info.CONTENT_PORTALID = Session.WorkingPortal().PORTALID;
            info.CONTENT_CATEGORYID = Convert.ToInt32(dropZones.SelectedValue);
            info.CONTENT_TYPE = Convert.ToInt32(drpContentType.SelectedValue);
            info.CONTENT_ZONEID = Convert.ToInt32(drpPerspective.SelectedValue);
            info.CONTENT_CREATEDATE = DateTime.Now;
            info.CONTENT_WAITTINGDATE = string.IsNullOrEmpty(txtDatetime.Text)
                                            ? DateTime.Now
                                            : Convert.ToDateTime(txtDatetime.Text);
            info.CONTENT_MODIFYDDATE = DateTime.Now;
            info.CONTENT_EXPIREDATE = string.IsNullOrEmpty(txtExprisedDate.Text)
                                          ? DateTime.MaxValue
                                          : Convert.ToDateTime(txtExprisedDate.Text);
            info.CONTENT_CREATEUSERID = currentUserId;
            info.CONTENT_CREATEUSERNAME = currentUserName;
            info.CONTENT_MODIFYUSERID = currentUserId;
            info.CONTENT_STATUS = (int) CMSWorkFlow.Archive;
            if (info.CONTENT_STATUS == 2)
                info.CONTENT_APPROVEUSERID = currentUserId;
            else
                info.CONTENT_APPROVEUSERID = 0;
            info.CONTENT_RANK = Convert.ToInt32(drpContentRank.SelectedValue);
            info.CONTENT_STATUS = (int) CMSWorkFlow.Archive;
            info.CONTENT_ISPAY = Convert.ToInt32(chkIsPay.Checked);
            info.CONTENT_ISCOMMENT = Convert.ToInt32(chkIsComment.Checked);
            info.CONTENT_UNUNICODE =
                UnicodeUtility.UnicodeToKoDau(info.CONTENT_HEADLINE + " " +
                                              RegexUtils.StripHtml(info.CONTENT_TEASER + " " + info.CONTENT_BODY, false));
            if (!string.IsNullOrEmpty(txtAvatar.Text))
                info.CONTENT_AVATAR = ImagesUtils.GetImage(txtAvatar.Text, Convert.ToInt32(txtAvatar2width.Text));
            if (!string.IsNullOrEmpty(txtSpecialAvatar.Text))
                info.CONTENT_PREAVATAR = ImagesUtils.GetImage(txtSpecialAvatar.Text, Convert.ToInt32(txtSpecialAvatarwidth.Text));
            return info;
        }

        protected void cmdAdd_Click(object sender, EventArgs e)
        {           
            string updateStatus = string.Empty;
            if (!string.IsNullOrEmpty(txtExprisedDate.Text))
            {
                if (DateTime.Compare(Convert.ToDateTime(txtDatetime.Text), Convert.ToDateTime(txtExprisedDate.Text)) < 0)
                {
                    updateStatus = Localization.GetText("MESSAGE", "MSG_DATETIME_ERROR");
                }
            }
            if (typeCreator > 0)
            {
                try
                {
                    TeenioContent info = GetContent();
                    if (typeCreator > 1)
                    {
                        info.CONTENT_STATUS = (int)CMSWorkFlow.Deploy;
                        info.CONTENT_APPROVEUSERID = currentUserId;
                        updateStatus = Localization.GetText("MESSAGE", "MSG_DEPLOY") + dropZones.SelectedItem.Text;
                    }
                    // Nếu quyền chỉ là biên tập viên (creater) thi bài sẽ được đăng vào mục chờ đăng
                    else
                    {
                        info.CONTENT_STATUS = (int)CMSWorkFlow.Archive;
                        updateStatus = Localization.GetText("MESSAGE", "MSG_ARCHIVE") + dropZones.SelectedItem.Text;
                    }
                    if (cmdSave.CommandName == "edit")
                    {
                        info.CONTENT_ID = Convert.ToInt32(cmdSave.CommandArgument);
                        ManagerFactory.DAOEntity.Update(info);
                    }
                    else
                        ManagerFactory.DAOEntity.Insert(info);
                    cmdHuy_Click(null, null);
                }
                catch (Exception exception)
                {
                    updateStatus = exception.Message;
                }
            }
            lblUpdateStatus.Text = updateStatus;
        }

        protected void cmdHuy_Click(object sender, EventArgs e)
        {
            txtHeadline.Text = string.Empty;
            txtTeaser.Text = string.Empty;
            txtRawContent.Value = string.Empty;
            txtSpecialAvatar.Text = string.Empty;
            txtAvatar.Text = string.Empty;
            txtAvatar2Height.Text = cfg.ThumbHeight.VALUE;
            txtAvatar2width.Text = cfg.ThumbWidth.VALUE;
            txtSpecialAvatarHeight.Text = cfg.SpecialHeight.VALUE;
            txtSpecialAvatarwidth.Text = cfg.SpecialWidth.VALUE;
            txtAvatarDes.Text = string.Empty;
            txtSource.Text = string.Empty;
            txtNoteBox.Text = string.Empty;
            dropZones.SelectedIndex = -1;
            txtDatetime.Text = DateTime.Now.ToString();
            txtExprisedDate.Text = string.Empty;
            drpContentRank.SelectedIndex = -1;
            chkIsComment.Checked = false;
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            TeenioContent info = GetContent();
            info.CONTENT_STATUS = (int) CMSWorkFlow.Archive;
            if (cmdSave.CommandName == "edit")
            {
                info.CONTENT_ID = Convert.ToInt32(cmdSave.CommandArgument);
                ManagerFactory.DAOEntity.Update(info);
            }
            else
                ManagerFactory.DAOEntity.Insert(info);
            lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_ARCHIVE") + dropZones.SelectedItem.Text;
            cmdHuy_Click(null, null);
        }

        protected void drpContentRank_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadZones();
        }

        private void LoadData(TeenioContent info)
        {
            txtHeadline.Text = info.CONTENT_HEADLINE;
            txtTeaser.Text = info.CONTENT_TEASER;
            txtRawContent.Value = info.CONTENT_BODY;
            txtSpecialAvatar.Text = (string.IsNullOrEmpty(info.CONTENT_PREAVATAR)) ? string.Empty : info.CONTENT_PREAVATAR;
            txtAvatar.Text = (string.IsNullOrEmpty(info.CONTENT_AVATAR)) ? string.Empty : info.CONTENT_AVATAR;
            txtAvatarDes.Text = info.CONTENT_AVATARDESCRIPTION;
            txtSource.Text = info.CONTENT_SOURCE;
            txtNoteBox.Text = info.CONTENT_METADATA;
            dropZones.SelectedValue = info.CONTENT_CATEGORYID.ToString();
            drpContentType.SelectedValue = info.CONTENT_TYPE.ToString();
            TeenioZone zone = ManagerFactory.DAOEntity.GetInfo(new TeenioZone() { ID = info.CONTENT_ZONEID });
            if (zone != null)
            {
                drpContentType.SelectedValue = zone.TYPE.ToString();
                LoadZones();
                drpPerspective.SelectedValue = info.CONTENT_ZONEID.ToString();
            }
            txtDatetime.Text = info.CONTENT_CREATEDATE.ToString();
            txtExprisedDate.Text = (info.CONTENT_EXPIREDATE.Year == DateTime.MaxValue.Year) ? string.Empty : info.CONTENT_EXPIREDATE.ToString();
            drpContentRank.SelectedValue = info.CONTENT_RANK.ToString();
            chkIsComment.Checked = Convert.ToBoolean(info.CONTENT_ISCOMMENT);
        }
    }
}